<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="自提点名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入自提点名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户id" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择用户id" clearable size="small">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="仓库id" prop="storageId">
        <el-select v-model="queryParams.storageId" placeholder="请选择仓库id" clearable size="small">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="gmtCreate">
        <el-date-picker clearable size="small"
          v-model="queryParams.gmtCreate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="详细地址" prop="detailAddress">
        <el-input
          v-model="queryParams.detailAddress"
          placeholder="请输入详细地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更新时间" prop="gmtUpdate">
        <el-date-picker clearable size="small"
          v-model="queryParams.gmtUpdate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="纬度" prop="lat">
        <el-input
          v-model="queryParams.lat"
          placeholder="请输入纬度"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="经度" prop="lng">
        <el-input
          v-model="queryParams.lng"
          placeholder="请输入经度"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
   <!--   <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['youxuan:merchants:add']"
        >新增</el-button>
      </el-col> -->
 <!--     <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['youxuan:merchants:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['youxuan:merchants:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['youxuan:merchants:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="merchantsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="团长的图片" align="center" prop="id" />
      <el-table-column label="自提点名称" align="center" prop="name" />
      <el-table-column label="用户id" align="center" prop="userId" />
      <el-table-column label="状态" align="center" >
      <template slot-scope="scope">
        <el-switch
          v-model="scope.row.status"
          active-value="1"
          inactive-value="0"
          @change="handleStatusChange(scope.row)"
        ></el-switch>
      </template>
      </el-table-column>
      <el-table-column label="仓库id" align="center" prop="storageId" />
      <el-table-column label="创建时间" align="center" prop="gmtCreate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtCreate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center" prop="detailAddress" />
      <el-table-column label="更新时间" align="center" prop="gmtUpdate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtUpdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="纬度" align="center" prop="lat" />
      <el-table-column label="经度" align="center" prop="lng" />
      <el-table-column label="团长的图片" align="center" prop="img" >
        <template slot-scope="scope">
            <img v-if="scope.row.img" style="text-align:center;display:block;width: 40px; height: 40px;" :src="scope.row.img" />
          </template>
        </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
        <!--  <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['youxuan:merchants:edit']"
          >修改</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['youxuan:merchants:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改自提点管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="自提点名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入自提点名称" />
        </el-form-item>
       <el-autocomplete
         v-model="form.userId"
         :fetch-suggestions="querySearchAsync"
         placeholder="请输入用户"
         @select="handleSelect"
       ></el-autocomplete>
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="仓库id" prop="storageId">
          <el-select v-model="form.storageId" placeholder="请选择仓库id">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input v-model="form.detailAddress" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="纬度" prop="lat">
          <el-input v-model="form.lat" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="经度" prop="lng">
          <el-input v-model="form.lng" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item >
            <baidu-map  class="map" :center="center" :zoom="zoom" @ready="handler"
            :scroll-wheel-zoom="true"
            @click="clickEvent"
            ak="33B192o1jPaqOHASGGAIkoMuwi8W76j3">
            	<!-- 地图控件位置 -->
                <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
                <!-- 获取城市列表 -->
                <bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT"></bm-city-list>
                <!-- 定位当前位置 -->
                <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT"  :showAddressBar="true" :autoLocation="true" @locationSuccess="getLoctionSuccess" ></bm-geolocation>
                <!-- 地图容器 -->
                <bm-view :style="{width:'75%',height: '500px'}"></bm-view>
             </baidu-map>
        </el-form-item>
        <el-form-item label="图片地址" prop="img">
          <el-upload class="avatar-uploader" accept="image/jpeg,image/png" action="oss-cn-beijing.aliyuncs.com"
                     :show-file-list="false"  :http-request="uploadPic" :on-success="handleAvatarSuccess" :before-upload="beforePicUpload">
                     <img v-if="imageUrl != ''" :src="imageUrl" class="avatar">
                     <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                   </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import zuuobiaoImg from '@/assets/zuobiao.png'
  import {BaiduMap,BmNavigation,BmView,BmGeolocation,BmCityList} from 'vue-baidu-map'
  import oss from '../../../utils/oss.js'
  import {
    listGoods,
    queryUploadToken
  } from "@/api/youxuan/goods";
import { listMerchants, getMerchants, delMerchants, addMerchants, updateMerchants, exportMerchants } from "@/api/youxuan/merchants";

export default {
   name: "mapDialog",
  	components: {
              BaiduMap,
              BmNavigation,
              BmView,
              BmGeolocation,
              BmCityList,

          },
  name: "Merchants",
  data() {
    return {
      center: {lng: 121.833138, lat: 39.081725},
                      zoom: 12,
                      mapVisible:false,
                      form:{
                          longitude:'',
                          latitude:'',
                          location:'',
                      },
                      clientHeight:document.documentElement.clientHeight-90, // 设置屏幕高度
                      iconUrl:zuuobiaoImg,//点击坐标标记
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 自提点管理表格数据
      merchantsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        userId: null,
        status: null,
        storageId: null,
        gmtCreate: null,
        detailAddress: null,
        gmtUpdate: null,
        lat: null,
        lng: null,
        img: null
      },
      imageUrl:'',
      uploadToken:null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // userId: [
        //   { required: true, message: "用户id不能为空", trigger: "change" }
        // ],
        // storageId: [
        //   { required: true, message: "仓库id不能为空", trigger: "change" }
        // ],
        detailAddress: [
          { required: true, message: "详细地址不能为空", trigger: "blur" }
        ],
        lat: [
          { required: true, message: "纬度不能为空", trigger: "blur" }
        ],
        lng: [
          { required: true, message: "经度不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("youxuan_acticity_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
       handler ({BMap, map}) {
              let _this = this;	// 设置一个临时变量指向vue实例；
              var geolocation = new BMap.Geolocation();
              geolocation.getCurrentPosition(function(r){
                console.log(r);
                _this.center = {lng: r.longitude, lat: r.latitude};		// 设置center属性值
                _this.autoLocationPoint = {lng: r.longitude, lat: r.latitude};		// 自定义覆盖物
                _this.initLocation = true;
              },{enableHighAccuracy: true})
                window.map = map;
            },
            //点击地图监听
            clickEvent(e){
              map.clearOverlays();
              let Icon_0 = new BMap.Icon(this.iconUrl, new BMap.Size(64, 64), {anchor: new BMap.Size(18, 32),imageSize: new BMap.Size(36, 36)});
              var myMarker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat),{icon: Icon_0});
              map.addOverlay(myMarker);
              //用所定位的经纬度查找所在地省市街道等信息
              var point = new BMap.Point(e.point.lng, e.point.lat);
              var gc = new BMap.Geocoder();
              let _this = this;
              gc.getLocation(point, function (rs) {
                var addComp = rs.addressComponents;
                //console.log(rs.address);//地址信息
                _this.form.location = rs.address;
              });
                this.form.lng = e.point.lng;
                this.form.lat = e.point.lat;
            },
            //定位成功回调
            getLoctionSuccess(point, AddressComponent, marker){
              map.clearOverlays();
              let Icon_0 = new BMap.Icon(this.iconUrl, new BMap.Size(64, 64), {anchor: new BMap.Size(18, 32),imageSize: new BMap.Size(36, 36)});
              var myMarker = new BMap.Marker(new BMap.Point(point.point.lng, point.point.lat),{icon: Icon_0});
              map.addOverlay(myMarker);
              this.form.longitude = point.point.lng;
              this.form.latitude = point.point.lat;
            },
            findlocation(){
              this.$emit("findlocdata",this.form)
              this.mapVisible = false
            },
            mapShow(){
              this.mapVisible = true
            },
    /** 查询自提点管理列表 */
    getList() {
      this.loading = true;
      listMerchants(this.queryParams).then(response => {
        this.merchantsList = response.rows;
        this.merchantsList.forEach(m=>{
          m.status = m.status.toString();
        })
        this.total = response.total;
        this.loading = false;
      });
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        userId: null,
        status: 0,
        storageId: null,
        gmtCreate: null,
        detailAddress: null,
        gmtUpdate: null,
        lat: null,
        lng: null,
        img: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
       this.queryToken();
      this.reset();
      this.open = true;
      this.title = "添加自提点管理";
    },
    handleStatusChange(row) {
      let text = row.status === "1" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.name + '"自提点吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return updateMerchants(row);
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "1" ? "0" : "1";
        });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
       this.queryToken();
      this.reset();
      const id = row.id || this.ids
      getMerchants(id).then(response => {
        this.form = response.data;
        this.center.lng = this.form.lng;
        this.center.lat = this.form.lat;
        this.imageUrl = this.form.img;
        this.open = true;
        this.title = "修改自提点管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.img = this.imageUrl;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMerchants(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMerchants(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    queryToken() {
           queryUploadToken().then(response => {
             if (response.code == 200)
               this.uploadToken = response.data;
           });
         },
         handleAvatarSuccess(res, file) {
            this.msgInfo('上传成功！');
             },beforePicUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isLt2M) {
              this.msgError('上传图片大小不能超过 2MB!');
            }
            return isLt2M;
          },
                async uploadPic(option) { //上传OSS
                  let that = this;
                  oss.setToken(that.uploadToken);
                  oss.ossUploadFile(option).then(res => {
                    console.log("fullUrl",res)
                    if (res != null) {
                      that.msgInfo('上传中...请耐心等待');
                      setTimeout(function (){
                        that.msgSuccess('上传成功！');
                        that.imageUrl = res.fullUrl;
                      }, 3000);
                    }
                  });
                },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除自提点管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delMerchants(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有自提点管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportMerchants(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
<style>
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }

    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
</style>
